// 顶点着色器程序
var VSHADER_SOURCE =
    'attribute vec4 a_Position;\n' +
    'attribute float a_PointSize;\n' +
    'void main() {\n' +
    ' gl_Position = a_Position;\n' + // 设置坐标
    ' gl_PointSize = a_PointSize;\n' + // 尺寸
    '}\n';

// 片元着色器程序
var FSHADER_SOURCE =
    'precision mediump float;\n' + // 精确限定词
    'uniform vec4 u_FragColor;\n' +
    'void main() {\n' +
    ' gl_FragColor = u_FragColor;\n' +
    '}\n';

function main() {
    // 获取 canvas 元素
    var canvas = document.getElementById('webgl');

    // 获取 WebGL 绘图上下文
    var gl = getWebGLContext(canvas, true);
    if(!gl) {
        console.log('Failed to get the rendering content of WebGL');
        return;
    }
    //初始着色器
    if(!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log('Failed to initialize shaders.');
        return;
    }
    // 获取 attribute 变量的存储位置
    var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
    if(a_Position < 0) {
        console.log('Failed to get the storage location of a_Position');
        return;
    }
    var a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');

    // 获取u_FragColor变量存储位置
    var u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
    if (!u_FragColor) {
    	console.log('Failed to get u_FragColor variable');
    	return;
    }

    // 将顶点位置传输给attribute变量
    //gl.vertexAttrib3f(a_Position, 0.0, 0.0, 0.0);
    canvas.onmousedown = function(event) {
        click(event, gl, canvas, a_Position, u_FragColor);
    };
    gl.vertexAttrib1f(a_PointSize, 10.0);

    //设置 <canvas> 背景色
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    // 清空 <canvas>
    gl.clear(gl.COLOR_BUFFER_BIT);

    // 绘制一个点
    //gl.drawArrays(gl.POINTS, 0, 1);
}

var g_points = []; //存储点击位置
var g_colors = []; //存储点颜色

function click(event, gl, canvas, a_Position, u_FragColor) {

    var x = event.clientX;
    var y = event.clientY;
    var rect = event.target.getBoundingClientRect();
    x = ((x - rect.left) - canvas.height / 2) / (canvas.height / 2);
    y = (canvas.width / 2 - (y - rect.top)) / (canvas.width / 2);

    // 坐标
    g_points.push([x, y]);
    // 颜色
    if(x >= 0 && y >= 0) { // 第一象限
        g_colors.push([1.0, 0.0, 0.0, 1.0]);
    } else if(x < 0 && y < 0) { // 第三象限
        g_colors.push([0.0, 1.0, 0.0, 1.0]);
    } else {
        g_colors.push([1.0, 1.0, 1.0, 1.0]);
    }
    // 清空 <canvas>
    gl.clear(gl.COLOR_BUFFER_BIT);

    var len = g_points.length;
    for(var i = 0; i < len; i++) {
        var xy = g_points[i];
        var rgba = g_colors[i];

        gl.vertexAttrib3f(a_Position, xy[0], xy[1], 0.0);
        gl.uniform4f(u_FragColor, rgba[0], rgba[1], rgba[2], rgba[3]);

        // 绘制点
        gl.drawArrays(gl.POINTS, 0, 1);
    }
}